#define _XOPEN_SOURCE
#include <func.h>
#include "head.h"
void get_salt(char *salt, char *pwd){
    int i, j;
    for(i = 0, j = 0; pwd[i] && j != 3; ++i){
        if(pwd[i] == '$')
            ++j;
    }
    strncpy(salt, pwd, i - 1);
}
int userLogin(int sockFd, char *userName, char *password){
    train_t t;
    //收到盐值
    int dataLength;
    char salt[30] = {0};
    recv(sockFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
    recv(sockFd, salt, dataLength, MSG_WAITALL);

    //混合加密为密文，发送密文
    char cryptograph[500] = {0};
    strcpy(cryptograph, crypt(password, salt));
    memset(&t, 0, sizeof(train_t));
    strcpy(t.buf, cryptograph);
    t.dataLength = strlen(t.buf);
    send(sockFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);

    char res;
    recv(sockFd, &res, 1, MSG_WAITALL);
    if(res == '1'){//合法用户
        return 1;
    }else{//非法用户
        close(sockFd);
        exit(0);
    }
}
int userRegister(int sockFd, char *userName, char *password){
    //发送要注册的名字和密码
    //printf("userName = %s, password = %s\n", userName, password);
    train_t t;
    strcpy(t.buf, userName);
    t.dataLength = strlen(t.buf);
    send(sockFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);
    
    memset(&t, 0, sizeof(train_t));
    strcpy(t.buf, password);
    t.dataLength = strlen(t.buf);
    send(sockFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);
}    